package quanlydoanvao.guiyeucau;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

import javax.faces.model.SelectItem;

import utils.DateUtils;
import utils.UtilsOnScopes;

import dbutil.ConnectDB;

public class BeanSearch{
	private String error;
	private String isExist;
	private String soHC_MaDoan;
	private String lydo;
	private String[] thaotac;
	private List<TableDisplay> listTable;

	public String getSoHC_MaDoan() {
		return soHC_MaDoan;
	}

	public void setSoHC_MaDoan(String soHC_MaDoan) {
		this.soHC_MaDoan = soHC_MaDoan;
	}

	public String getLydo() {
		return lydo;
	}

	public void setLydo(String lydo) {
		this.lydo = lydo;
	}

	public String[] getThaotac() {
		return thaotac;
	}

	public void setThaotac(String[] thaotac) {
		this.thaotac = thaotac;
	}
	
	
	public String getError() {
		return error;
	}
	

	public String getIsExist() {
		return isExist;
	}

	public void setIsExist(String isExist) {
		this.isExist = isExist;
	}

	public List<TableDisplay> getListTable() {
		this.table();
		return listTable;
	}

	public void setListTable(List<TableDisplay> listTable) {
		this.listTable = listTable;
	}

	public void setError(String error) {
		this.error = error;
	}
	
	/**************************************
	 * Method name		: getSelectItem
	 * Return type		: SelectItem[]
	 * Decription		:tao ra cac selectItem
	 * Created date		: Jun 16, 2008
	 * Author			: Honglk
	 **************************************/
	public SelectItem[] getSelectItem(){
		SelectItem[] arr = new SelectItem[2];
		arr[0] = new SelectItem("xoa","Xóa");
		arr[1] = new SelectItem("sua","Sửa");
		return arr;
	}

	/**************************************
	 * Method name		: send
	 * Return type		: String
	 * Decription		:Gui yeu cau
	 * Created date		: Jun 13, 2008
	 * Author			: Honglk
	 **************************************/
	public String send() {
		ConnectDB.connectDB();
		String error = "";
		if (this.soHC_MaDoan == null || this.soHC_MaDoan.equals("")) {
			error = "Bạn phải nhập mã đoàn vào";
			this.setError(error);
			return this.error;
		} else {
			String userName = UtilsOnScopes.getUserName();
			String xoa = "0";
			String sua = "0";
			if (this.checkExist(this.soHC_MaDoan) == false) {
				this.setError("Mã đoàn không tồn tại !");
				return this.error;
			}//Them (5-7-2008)
			else if(this.checkHC(soHC_MaDoan) == false){
				this.setError("Mã đoàn này đã có người yêu cầu !");
				return this.error;
			}
				//End
			else if (this.lydo == null || this.lydo.equalsIgnoreCase("")) {
				this.setError("Bạn chưa nhập lý do !");
				return this.error;
			}
			// xua ly checkbox
			else if (this.thaotac.length == 0) {
				this.setError("Bạn chưa chọn thao tác !");
				return this.error;
			} else if (this.thaotac.length == 1) {
				if (this.thaotac[0].equalsIgnoreCase("xoa")) {
					xoa = "1";
				} else if (this.thaotac[0].equalsIgnoreCase("sua")) {
					sua = "1";
				}
			} else if (this.thaotac.length == 2) {
				xoa = this.thaotac[0].equals("xoa") ? "1" : "0";
				sua = this.thaotac[1].equals("sua") ? "1" : "0";
			}
			String lydo = this.lydo;
			String ngayYeuCau = DateUtils.LayNgayThangHienTai1();
			Date ngayYeuCauDate = Date.valueOf(ngayYeuCau);
			try {
				List<String> list = this.cutString(this.soHC_MaDoan);
				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						PreparedStatement preStat = ConnectDB.connect
								.prepareStatement("INSERT INTO phanquyenxoasua(username,sohc_idgroup,xoa,sua,"
										+ "ghichu,ngayyeucau,daduyet,khoa) "
										+ "VALUES(?,?,?,?,?,?,?,?)");
						preStat.setString(1, userName);
						preStat.setString(2, list.get(i));
						preStat.setString(3, xoa);
						preStat.setString(4, sua);
						preStat.setString(5, lydo);
						preStat.setDate(6, ngayYeuCauDate);
						preStat.setString(7, "0");
						preStat.setString(8, "0");
						preStat.executeUpdate();
					}
					this.setError("Bạn đã gửi yêu cầu thành công !");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		//this.reset1();
		return "okguiyeucau";
	}
	
	/**************************************
	 * Method name		: cutString
	 * Return type		: List<String>
	 * Decription		:cat chuoi
	 * Created date		: Jun 16, 2008
	 * Author			: Honglk
	 **************************************/
	private List<String> cutString(String soHC_MaDoan){
		List<String> listStr = new ArrayList<String>();
		if( soHC_MaDoan != null && !( soHC_MaDoan.equals(""))){
			StringTokenizer token = new StringTokenizer( soHC_MaDoan,",[");
			while(token.hasMoreTokens()){
				listStr.add(token.nextToken());
			}
		}
		return listStr;
	}
	
	/**************************************
	 * Method name		: helpCheck
	 * Return type		: boolean
	 * Decription		:Ho tro cho ham check
	 * Created date		: Jun 16, 2008
	 * Author			: Honglk
	 **************************************/
	private boolean helpCheck(String soHC_MaDoan){
		boolean result = false;
		String SQLDV = "SELECT madoan FROM doanvao WHERE flagdelete = 0 and LOWER(TRIM(madoan)) LIKE LOWER(TRIM('"
			+ soHC_MaDoan + "'))";
		ArrayList<HashMap<String, Object>> arrayDV = ConnectDB
		.getDataTypeList(SQLDV);
		try {
			if (arrayDV!= null && arrayDV.size() > 0) {
				result = true;
			}
			else {
				result = false;
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}
	
	/**************************************
	 * Method name		: checkExist
	 * Return type		: boolean
	 * Decription		:Kiem tra xem soHC hoac madoan nhap vao co ton tai hay khong?
	 * Created date		: Jun 16, 2008
	 * Author			: Honglk
	 **************************************/
	private boolean checkExist(String soHC_MaDoan) {
		boolean result = false;
		List<String> listStr = this.cutString(soHC_MaDoan);
		if(listStr != null && listStr.size() > 0){
			for (int i = 0; i < listStr.size(); i++) {
				result = this.helpCheck(listStr.get(i));
			}
		}
		return result;
	}
	
	/**************************************
	 * Method name		: checkHC
	 * Return type		: boolean
	 * Decription		:Kiem tra xem:trong cung ngay chi co 1 nguoi duoc yeu cau thao tren so HC nay
	 * Created date		: Jul 5, 2008
	 * Author			: Honglk
	 **************************************/
	private boolean checkHC(String soHC_MaDoan) {
		boolean result = false;
		List<String> listStr = this.cutString(soHC_MaDoan);
		if(listStr != null && listStr.size() > 0){
			for (int i = 0; i < listStr.size(); i++) {
				result = this.helpCheckHC(listStr.get(i));
			}
		}
		return result;
	}
	
	/**************************************
	 * Method name		: helpCheckHC
	 * Return type		: boolean
	 * Decription		:ho tro cho ham checkHC
	 * Created date		: Jul 5, 2008
	 * Author			: Honglk
	 **************************************/
	private boolean helpCheckHC(String soHC_MaDoan){
		boolean result = false;
		String userName = UtilsOnScopes.getUserName();
		String ngayYeuCau = DateUtils.LayNgayThangHienTai1();
		Date ngayYeuCauDate = Date.valueOf(ngayYeuCau);
		String SQL= "SELECT B.username FROM phanquyenxoasua B WHERE " +
										" B.sohc_idgroup ='" +soHC_MaDoan+"' " +
										" AND B.ngayyeucau ='"+ngayYeuCauDate+"'";
		System.out.println(SQL);
		ArrayList<HashMap<String, Object>> array = ConnectDB
		.getDataTypeList(SQL);
		try {
			if (array.size() > 0) {
				HashMap<String, Object> hash = new HashMap<String, Object>();
				hash = (HashMap<String, Object>) array.get(0);
				String name = hash.get("username").toString();
				if(name.equalsIgnoreCase(userName)){
					return result = true;
				}
				else 
					return result = false;
			}else{
				result = true;
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}
	
	/**************************************
	 * Method name		: reset
	 * Return type		: String
	 * Decription		:rết lai du lieu
	 * Created date		: Jun 16, 2008
	 * Author			: Honglk
	 **************************************/
	public String reset(){
		UtilsOnScopes.getSession().removeAttribute("beanSearch");
		this.setError("");
		this.setLydo("");
		this.setSoHC_MaDoan("");
		return "okguiyeucau";
		
	}
	/**************************************
	 * Method name		: reset1
	 * Return type		: String
	 * Decription		:reset lai du lieu nhung reset error
	 * Created date		: Jun 16, 2008
	 * Author			: Honglk
	 **************************************/
	public void reset1(){
		UtilsOnScopes.getSession().removeAttribute("beanSearch");
		
	}
	/**************************************
	 * Method name		: table
	 * Return type		: List<TableDisplay>
	 * Decription		:Hien thi ra table ben giao dien,hien thi nhung record
	 *                   cua chinh user do va trong vong 1 thang
	 * Created date		: Jun 13, 2008
	 * Author			: Honglk
	 **************************************/
	public List<TableDisplay> table(){
		List<TableDisplay> li = new ArrayList<TableDisplay>();
		String ngayHienTai = DateUtils.LayNgayThangHienTai1();
		String truoc1Thang  = DateUtils.truoc1Thang(ngayHienTai);
		Date ngayHienTaiDateSQL = Date.valueOf(ngayHienTai);
		Date truoc1ThangDateSQL = Date.valueOf(truoc1Thang);
		String userName = UtilsOnScopes.getUserName();
		String SQL = "SELECT * FROM phanquyenxoasua A WHERE A.username LIKE '"+userName +"' AND A.ngayyeucau BETWEEN '"
			         +truoc1ThangDateSQL +"' AND '" +ngayHienTaiDateSQL +"' ORDER BY  A.ngayyeucau DESC";
		ArrayList<HashMap<String, Object>> array = ConnectDB
		.getDataTypeList(SQL);
		if (array.size() > 0) {
			HashMap<String, Object> hash = new HashMap<String, Object>();
			int stt = 0;
			for (int i = 0; i < array.size(); i++) {
				stt = i + 1;
				hash = (HashMap<String, Object>) array.get(i);
				TableDisplay table = new TableDisplay();
				table.setStt(String.valueOf(stt));
				table.setSoHC_Madoan(hash.get("sohc_idgroup").toString());
				table.setLydo(hash.get("ghichu").toString());
				String ngayYeuCau = DateUtils.formatDate(hash.get("ngayyeucau").toString());
				table.setNgayYeuCau(ngayYeuCau);
				table.setDaDuyet(String.valueOf(hash.get("daduyet")).equals("1")?"Duyệt":"Chưa");
				table.setThaoTac(hash.get("xoa").toString(), hash.get("sua").toString());
				table.setKhoa(String.valueOf(hash.get("khoa")).equals("1")?"Khóa":"Chưa");
				li.add(table);
			}
		}
		this.setListTable(li);
		return li;
	}
	public static void main(String[] args) {
		BeanSearch a  = new BeanSearch();
		System.out.println(a.helpCheckHC("HC0000"));
	}

}
